/*------------------------------------------------------------------------------*\
**   Copyright 2008-2009 Jonhnny Weslley                                        **
**                                                                              **
**   Licensed under the Apache License, Version 2.0 (the "License");            **
**   you may not use this file except in compliance with the License.           **
**   You may obtain a copy of the License at                                    **
**                                                                              **
**       http://www.apache.org/licenses/LICENSE-2.0                             **
**                                                                              **
**   Unless required by applicable law or agreed to in writing, software        **
**   distributed under the License is distributed on an "AS IS" BASIS,          **
**   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   **
**   See the License for the specific language governing permissions and        **
**   limitations under the License.                                             **
\*------------------------------------------------------------------------------*/

package org.scalashell

trait MessageSource {

  def apply(key: String): String

  def apply(key: String, args: Object*): String

}


class CompositeMessageSource extends MessageSource with util.StringReplacer {

  import java.util.ResourceBundle
  import scala.collection.mutable.ListBuffer

  val beginToken = "$("
  val endToken = ")"

  private final val bundles = new ListBuffer[ResourceBundle]
  private final val sysprops = System.getProperties

  def apply(key: String) = apply(key, Nil)

  def apply(key: String, args: Object*) = {
    val index = bundles findIndexOf (_ containsKey key)
    if (index > -1) {
      val value = bundles(index) getString key
      val msg = java.text.MessageFormat.format(value, args.toArray)
      replace(msg)

    } else if (sysprops containsKey key) {
      sysprops getProperty key

    } else {
      undefined(key)
    }
  }

  private def undefined(key: String) = "!" + key + "!"

  def addSource(name: String) = bundles + (ResourceBundle getBundle name)

  def evaluate(text: String) = apply(text)

}